<template>
  <el-dialog
      :model-value="dialogVisible"
    title="导入云主机"
    width="700px"
    :before-close="dialogClose"
  >
    <el-steps :active="active" align-center style="margin-bottom: 10%">
      <el-step title="公有云"></el-step>
      <el-step title="访问凭据"></el-step>
      <el-step title="导入确认"></el-step>
    </el-steps>

    <el-form
      ref="formRef"
      :model="ruleForm"
      :rules="rules"
      label-position="right"
      label-width="155px"
    >
      <!--第一步-->

      <!-- label-width="0px" -->
      <div v-show="active == 1">
        <el-form-item prop="cloud">
          <el-radio-group v-model="ruleForm.cloud">
            <el-radio label="aliyun">
            
              阿里云
            </el-radio>
            <el-radio label="tencent">
            
              腾讯云
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!--第二步-->
      <div v-show="active == 2">
        <el-form-item label="平台AK账号" prop="platformAccountId">
          <el-select
            v-model="ruleForm.platformAccountId"
            filterable
            clearable
            @click="getPlatformAccount"
            placeholder="选择AccessKey"
          >
            <el-option
              v-for="item in platformAccounts"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="AccessKey ID:" prop="secret_id">
          <el-input v-model="ruleForm.secret_id" clearable></el-input>
        </el-form-item>
        <el-form-item label="AccessKey Secret:" prop="secret_key">
          <el-input
            v-model="ruleForm.secret_key"
            clearable
          ></el-input>

          <el-link
            v-if="ruleForm.cloud == 'aliyun'"
            href="https://ram.console.aliyun.com/manage/ak"
            target="_blank"
            type="primary"
            >如何获取AccessKey？</el-link
          >
          <el-link
            v-if="ruleForm.cloud == 'tencent'"
            href="https://console.cloud.tencent.com/cam/capi"
            target="_blank"
            type="primary"
            >如何获取AccessKey？</el-link
          >
        </el-form-item>
      </div>
      <!--第三步-->
      <div v-show="active == 3">
        <el-form-item label="选择区域：" prop="region">
          <el-select
            class="m-2"
            v-model="ruleForm.region"
            @click="getCloudRegion"
            placeholder="请选择"
            style="width: 100%"
          >
            <el-option
              v-for="item in cloudRegion"
              :key="item.region_id"
              :label="item.region_name"
              :value="item.region_id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="连接方式: " prop="connect_type" required>
          <el-col :span="1.5">
            <el-tag size="large" type="info">IP</el-tag>
          </el-col>
          <el-col :span="7" :offset="1">
            <el-radio-group v-model="ruleForm.connect_type">
              <el-radio :label="1">公网</el-radio>
              <el-radio :label="2">内网</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>

        <el-form-item label="关联SSH账号:" style="width: 100%" prop="ssh_id">
          <el-select
            v-model="ruleForm.ssh_id"
            filterable
            clearable
            @click="getsshs"
            placeholder="选择账号"
          >
            <el-option
              v-for="item in sshOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </div>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose" v-if="active == 1">取消</el-button>
        <el-button type="primary" @click="dialogToggle('pre')" v-if="active > 1"
          >上一步</el-button
        >
        <el-button
          type="primary"
          @click="dialogToggle('next')"
          v-if="active < 3"
          >下一步</el-button
        >
        <el-button type="primary" :loading="loading" @click="submit" v-if="active == 3"
          >确定</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { getPlatformAccounts, getPlatformAccount } from "@/api/cloudPlatform/platform";
import { getsshs } from "@/api/asset/ssh";
export default {
  name: "CloudCreate",
  props: {
    dialogVisible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ruleForm: {
        cloud: "",
        platformAccountId: "",
        secret_id: "",
        secret_key: "",
        region: "",
        server_group: "",
        ssh_id: "",
        connect_type: 1, // 默认使用公网还是内网
      },
      rules: {
        cloud: [{ required: true, message: "请选择", trigger: "blur" }],
        secret_id: [
          { required: true, message: "请输入密钥ID", trigger: "blur" },
          { min: 20, message: "密钥ID长度应不小于20个字符", trigger: "blur" },
        ],
        secret_key: [
          { required: true, message: "请输入密钥Key", trigger: "blur" },
          { min: 20, message: "密钥Key长度应不小于20个字符", trigger: "blur" },
        ],
        region: [
          { required: true, message: "请选择资源所在区域", trigger: "blur" },
        ],
        server_group: [
          { required: true, message: "请选择资源分组", trigger: "blur" },
        ],
        ssh_id: [
          { required: false, message: "请选择关联登录账号", trigger: "blur" },
        ],
      },
      cloudRegion: "",
      active: 1,
      idc: "",
      serverGroup: "",
      loading:false,
      platformAccounts: [],
      sshOptions: [],
      groupOptions: [],
    };
  },
  methods: {
    // 查询凭证
    getsshs() {
      getsshs().then((response) => {
        this.sshOptions = response.data.results;
        const passwd = [];
        for (let i in this.sshOptions) {
          passwd.push(
            this.sshOptions[i].name +
              "-" +
              this.sshOptions[i].authentication_type
          );
        }
        console.log("passwd 获取凭证:", passwd);
      });
    },
    //    平台AK
    getPlatformAccount() {
      getPlatformAccounts(this.ruleForm).then((res) => {
        this.platformAccounts = res.data.results;
        console.log("platformAccounts ", this.platformAccounts);
      });
    },
    submit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          console.log("this.ruleForm+", this.ruleForm);
          this.loading = true
          if (this.ruleForm.cloud == "aliyun") {
            this.$axios.post("/asset/aliyun_cloud/update/", this.ruleForm)
            .then((response) => {
                if (response.data.code == 20000) {
                  this.$message.success(response.data.detail);
                  //   this.$parent.getData();
                } else {
                  this.$message.error(response.data.detail);
                }
                this.loading = false
                this.dialogClose(); // 关闭窗口
                
              });
          } else if (this.ruleForm.cloud == "tencent") {
            this.$axios
              .post("/cmdb/tencent_cloud/", this.ruleForm)
              .then((response) => {
                if (response.code == 20000) {
                  this.$message.success(response.data.detail);
                  //   this.$parent.getData();
                  this.dialogClose(); // 关闭窗口
                } else {
                  this.$message.error(response.data.detail);
                }
              });
          }
        //   this.$message.error("格式错误！");
        }
      });
    },
    // 点击关闭，子组件通知父组件更新属性
    dialogClose() {
      console.log("子组件窗口关闭,通知父组件");
      this.$emit("close"); // 通知父组件
      this.$emit("search");
    },
    // 云主机导入第一步和第二步对话框切换
    dialogToggle(action) {
      if (action == "pre") {
        if (this.active-- < 2) {
          this.active = 1;
        }
      } else if (action == "next") {
        if (this.active++ > 3) {
          this.active = 1;
        }
      }
    },
    // 获取云平台区域列表
    getCloudRegion() {
      if (this.ruleForm.cloud == "aliyun") {
        // 携带密钥请求

        console.log("获取云平台区域列表:", this.ruleForm);
        this.$axios.post("/asset/aliyun_cloud/region/", this.ruleForm).then((response) => {
            this.cloudRegion = response.data.results;
            this.$message.success(response.data.detail);
          });
      } else if (this.ruleForm.cloud == "tencent") {
        this.$axios.get("/cmdb/tencent_cloud/", { params: this.ruleForm })
          .then((response) => {
            this.cloudRegion = response.data.results;
            this.$message.success(response.data.detail);
          });
      } else {
        this.$message.error("请选择公有云！");
      }
    },
  },

  watch: {
    // 监听自动渲染
    "ruleForm.platformAccountId": {
      handler: function () {
        if (this.ruleForm.platformAccountId) {
          getPlatformAccount(this.ruleForm.platformAccountId).then(
            (response) => {
              let data = response.data;
              console.log("data:", data);
              console.log(
                "platformAccountId:",
                this.ruleForm.platformAccountId
              );
              // 给accesskey自动赋值
              this.ruleForm.secret_key = data.secret;
              this.ruleForm.secret_id = data.accesskey;
            }
          );
        }
      },
    },
  },
};
</script>